import React, {useState} from 'react';
import {View, Button, Image, StyleSheet, Text, Alert} from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';

const ImagePickerDemo = () => {
  const [imagePath, setImagePath] = useState(null);
  const [error, setError] = useState('');

  const handleSelectImage = () => {
    ImagePicker.openPicker({
      width: 300,
      height: 300,
      cropping: true,
      freeStyleCropEnabled: true, // 允许自由裁剪
      includeBase64: false,
      multiple: false,
    })
      .then(image => {
        setImagePath(image.path);
        setError('');
      })
      .catch(error => {
        if (error.code === 'E_CANCELLED') {
          Alert.alert('操作取消', '您取消了图片选择');
        } else {
          setError(`错误: ${error.message}`);
        }
      });
  };

  const handleTakePhoto = () => {
    ImagePicker.openCamera({
      width: 300,
      height: 300,
      cropping: true,
      includeBase64: false,
    })
      .then(image => {
        setImagePath(image.path);
        setError('');
      })
      .catch(error => {
        setError(`相机错误: ${error.message}`);
      });
  };

  return (
    <View style={styles.container}>
      <Button title="从相册选择" onPress={handleSelectImage} />
      <Button title="拍照" onPress={handleTakePhoto} style={{marginTop: 20}} />
      {error ? <Text style={styles.error}>{error}</Text> : null}
      {imagePath && (
        <Image
          source={{uri: imagePath}}
          style={styles.previewImage}
          resizeMode="contain"
        />
      )}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    padding: 20,
    justifyContent: 'center',
    alignItems: 'center',
  },
  previewImage: {
    width: 250,
    height: 250,
    marginTop: 30,
    borderRadius: 8,
  },
  error: {
    color: 'red',
    marginTop: 10,
  },
});

export default ImagePickerDemo;
